package com.itheima.utils;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jms.TextMessage;

@Component
public class ActiveMqUtil {

    private static JmsTemplate jmsTemplate;

    @Autowired
    private JmsTemplate jmsTemplate1;

    @PostConstruct
    public void setProperties(){
        jmsTemplate = jmsTemplate1;
    }

    /**
     * 发送消息
     * @param message
     * @param mqName
     * @param time 单位:毫秒
     */
    public static void sendMsg(String message, String mqName, Long time) {
        if (time != null && time > 0) {// 延时消息
            jmsTemplate.send(mqName, session -> {
                TextMessage tm = session.createTextMessage(message);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
                return tm;
            });
        } else {  // 即时消息
            jmsTemplate.send(mqName, session -> session.createTextMessage(message));
        }
    }

}
